package com.qf.controller;

import cn.hutool.core.date.DateUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.qf.dao.OrderDao;
import com.qf.service.OrderService;
import com.qf.utils.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
public class OrderController {

    @Value("${alipay.publickey}")
    private String publickey;
    @Value("${alipay.signtype}")
    private String signtype;
    @Value("${alipay.charset}")
    private String charset;

    @Autowired
    OrderService orderService;

    @Autowired(required = false)
    OrderDao orderDao;

    @GetMapping("/order")
    public ResultMsg generate(int cid, HttpServletRequest request){
        return orderService.generate(cid, request);
    }

    @PostMapping("/order/status")
    public ResultMsg status(HttpServletRequest request) {
        //获得请求信息中的orderid
        Map<String, String> paramsMap =convert(request); //...  //将异步通知中收到的所有参数都存放到 map 中
        boolean  signVerified = false;  //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(paramsMap, publickey, charset, signtype);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if (signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商家自身业务处理，校验失败返回failure
            //在paramsMap中获得支付的相关信息：支付的时间、支付的结果、订单编号
            String oid=paramsMap.get("out_trade_no");
            //hutool
            Date paytime= DateUtil.parseTime(paramsMap.get("notify_time"));
            int status=paramsMap.get("trade_status").equals("TRADE_SUCCESS")?1:0;
            //更改订单的状态;
            int res=orderDao.updateStatus(oid,paytime,status);
            if(res==1)
                return new ResultMsg().success();
            return new ResultMsg().faild(100,"支付失败");
        } else {
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            return new ResultMsg().faild(100,"支付失败");
        }
    }
    //直接使用：将请求的所有信息转为Map
    private Map<String, String> convert(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }
        return retMap;

    }

}
